package com.wkk.authorization.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkk.authentication.entity.UmsUser;
import com.wkk.authentication.mapper.UmsUserMapper;
import com.wkk.authorization.common.AuthorizationConstant;
import com.wkk.authorization.entity.UmsRole;
import com.wkk.authorization.entity.UmsUserRole;
import com.wkk.authorization.mapper.UmsRoleMapper;
import com.wkk.authorization.mapper.UmsUserRoleMapper;
import com.wkk.authorization.service.UmsUserRoleService;
import com.wkk.constant.CommonConstant;
import com.wkk.exception.NoBugException;
import com.wkk.utils.NoBugTools;
import com.wkk.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author : WangKeKe
 * @date : 2020/10/5 12:42
 * Description : 用户角色关联服务层实现类
 */


@Service
@Slf4j
public class UmsUserRoleServiceImpl extends ServiceImpl<UmsUserRoleMapper, UmsUserRole> implements UmsUserRoleService {

    @Autowired
    private UmsUserMapper umsUserMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UmsRoleMapper umsRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserRole(String userId, String roleIds) {
        UmsUser umsUser = null;
        if (redisUtil.hasKey(CommonConstant.PREFIX_USER + userId)) {
            // 如果存在缓存则查询缓存
            umsUser = (UmsUser) redisUtil.get(CommonConstant.PREFIX_USER + userId);
            log.info("角色更新查询查询用户信息依靠 >>>>> 缓存");
        } else {
            umsUser = umsUserMapper.selectById(userId);
            if (NoBugTools.isNotEmpty(umsUser)) {
                redisUtil.set(CommonConstant.PREFIX_USER + umsUser.getId(), umsUser, CommonConstant.REFRESH_TOKEN_TIME);
            }
        }
        if (NoBugTools.isEmpty(umsUser)) {
            throw new NoBugException("无法找到当前用户ID对应的用户");
        }

        // 先删除此userId下的所有角色，然后再将这些角色的ID分割插入数据库即可
        baseMapper.delete(new LambdaQueryWrapper<UmsUserRole>().eq(UmsUserRole::getUserId, userId));
        List<String> roleIdList = Arrays.asList(roleIds.split(","));

        if (NoBugTools.listIsEmpty(roleIdList)) {
            throw new NoBugException("角色ID组为空");
        }

        UmsUserRole userRole = new UmsUserRole();
        userRole.setUserId(userId);
        for (String roleId : roleIdList) {
            UmsRole role = (UmsRole) redisUtil.get(AuthorizationConstant.ROLE_CACHE_PREFIX + roleId);
            if (NoBugTools.isEmpty(role)) {
                // 如果缓存中无法获取角色则查询数据库
                role = umsRoleMapper.selectById(roleId);
                if (NoBugTools.isEmpty(role)) {
                    throw new NoBugException("无法查询到该角色ID对应的角色信息ID：" + roleId);
                }
                redisUtil.set(AuthorizationConstant.ROLE_CACHE_PREFIX + userId, role, AuthorizationConstant.CACHE_TIME);
            }
            userRole.setRoleId(roleId).setId(null);
            baseMapper.insert(userRole);
            log.info("用户与角色关联成功：" + userRole.getId());
        }
        return true;
    }
}
